import json

from flask import request, jsonify, g

from cfg import UserModel
from cfg.token import verify_token

# 定义需要进行校验的路由前缀
VALIDATE_ROUTES = ['/auth/login', '/auth/register', "/", "/auth/send"]


# 自定义中间件函数
def token_validation_middleware():
    """
    校验 Token 的中间件
    """
    tmp = request
    # 检查请求的路径是否需要进行校验
    if any(request.path.startswith(route) for route in VALIDATE_ROUTES):
        return

    # 获取请求头中的 Token
    token = request.headers.get('Authorization')
    # 校验 Token
    if token is None:
        return invalid_token()
    else:
        data = verify_token(token)
        if data is None:
            return invalid_token()
        g.user = UserModel(
            id=data["id"],
            username=data["username"],
            email=data["email"],
            join_time=data["join_time"],
            age=data["age"],
            gender=data["gender"],
            tel=data["tel"]
        )


def clear_token(exception=None):
    """
    清除 g 对象中的 token_data
    """
    if hasattr(g, 'user'):
        g.user = None
        delattr(g, 'user')


def invalid_token():
    """
    校验失败的响应
    """
    # 如果校验失败，返回错误响应
    response = jsonify({'error': 'Forbidden'})
    response.status_code = 403  # Unauthorized
    return response
